﻿
using System;
using System.Globalization;
using System.Management;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using iBackupExplorer.Properties;

namespace iBackupExplorer.Utils
{
    class Utils
    {
        public static String ConvertFromUnix(int value)
        {
            DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            date = date.AddSeconds(value).ToLocalTime();
            return date.ToLongDateString();
        }
        public static String ConvertFromMac(int value)
        {
            DateTime date = new DateTime(2001, 1, 1, 0, 0, 0, 0);
            date = date.AddSeconds(value).ToLocalTime();
            return date.ToLongDateString();
        }

        public static Version GetAppVersion()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Version currentVersion = assembly.GetName().Version;
            return currentVersion;
        }
        public static string GetExternalIP()
        {
            const string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
            WebClient wc = new WebClient();
            UTF8Encoding utf8 = new UTF8Encoding();
            try
            {
                string ipaddr = null;
                bool done = false;

                wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler((object sender, DownloadDataCompletedEventArgs e) =>
                {
                    try
                    {
                        ipaddr = utf8.GetString(e.Result);
                        done = true;
                    }
                    catch (Exception)
                    {
                        done = true;
                    }
                });

                wc.DownloadDataAsync(new Uri(whatIsMyIp));
                DateTime startTime = DateTime.Now;
                while (!done)
                {
                    TimeSpan sp = DateTime.Now - startTime;

                    // We should get a response in less than timeout.
                    // If not, we cancel all and return the internal IP Address
                    if (sp.TotalMilliseconds > 2000)
                    {
                        done = true;
                        wc.CancelAsync();
                    }
                }
                return ipaddr;
            }
            catch
            {
                return null;
            }
            finally
            {
                wc.Dispose();
            }
        }
        private static string GetOsName()
        {

            const string os_query = "SELECT * FROM Win32_OperatingSystem";
            string strName = string.Empty;
            ManagementObjectSearcher os_searcher = new ManagementObjectSearcher(os_query);
            
            foreach (ManagementObject info in os_searcher.Get())
                strName = info.Properties["Caption"].Value.ToString().Trim();
            
            return strName;

        }


        private static void logExceptionAsync(Exception ex, string param)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Settings.Default.FirstIp) == false)
                {
                    const string connectionString =
                        "SERVER=instance33492.db.xeround.com;Port=14558;DATABASE=Logs;UID=app;PASSWORD=appwriter;";
                    MySqlConnection connection = new MySqlConnection(connectionString);
                    string query =
                        "INSERT INTO exception (Message,Source,TargetSite,InnerException,StackTrace,Ip,BinaryVersion) VALUES('" +
                        ex.Message.Replace("'","") + Environment.NewLine + "Param :" + param + "','" +
                        ex.Source + "','" +
                        ex.TargetSite + "','" +
                        ex.InnerException + "','" +
                        ex.StackTrace + "','" +
                        Settings.Default.FirstIp + "','" +
                        GetAppVersion() + "')";
                    connection.Open();
                    new MySqlCommand(query, connection).ExecuteNonQuery();
                    connection.Close();
                }

            }
            catch (Exception)
            {

            }
        }
        public static void LogException(Exception ex, string strParams)
        {
            Task.Factory.StartNew(() => logExceptionAsync(ex, strParams));
        }

        public static void notifyEvent(string strUsage)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Settings.Default.FirstIp) == false)
                {
                    const string connectionString = "SERVER=instance33492.db.xeround.com;Port=14558;DATABASE=Logs;UID=app;PASSWORD=appwriter;";
                    MySqlConnection connection = new MySqlConnection(connectionString);
                    string query = "INSERT INTO usages (BinaryVersion,Event,OSName,OSLanguage,Ip) VALUES('" +
                                                                                Assembly.GetExecutingAssembly().GetName().Version + "','" +
                                                                                strUsage + "','" +
                                                                                GetOsName() + "','" +
                                                                                CultureInfo.CurrentCulture.DisplayName + "','" +
                                                                                Settings.Default.FirstIp + "')";
                    connection.Open();
                    new MySqlCommand(query, connection).ExecuteNonQuery();
                    connection.Close();
                }
            }
            catch (Exception)
            { }
        }

    }
}
